package ee.wm.ilmataat.xml;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import ee.wm.ilmataat.Location;

public class CoordinatesXmlHandler extends DefaultHandler {

	Boolean currentElement;
	String currentValue;
	private Map<String, Location> locations;
	private Location currentLocation;
	String currentStation;

	public Map<String, Location> getLocations() {
		return locations;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		currentElement = true;
		if (localName.equals("coordinates")) {
			locations = new HashMap<String, Location>();
		} else if (localName.equals("station")) {
			currentLocation = new Location();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		currentElement = false;
		if (localName.equalsIgnoreCase("latitude")) {
			currentLocation.setLatitude(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("longitude")) {
			currentLocation.setLongitude(new BigDecimal(currentValue));
		} else if (localName.equalsIgnoreCase("name")) {
			currentStation = currentValue;
		} else if (localName.equalsIgnoreCase("station")) {
			locations.put(currentStation, currentLocation);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (currentElement) {
			currentValue = new String(ch, start, length);
			currentElement = false;
		}
	}

}